package com.cskaoyan.service;

import com.cskaoyan.bean.MarketCoupon;
import com.cskaoyan.bean.MarketCouponExample;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.Random;

public class AdminCouponServiceImpl implements AdminCouponService {
    @Override
    public CommonData<MarketCoupon> list(String name, Short type, Short status, Integer page, Integer limit, String sort, String order) {
        MarketCouponExample example = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();

        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        if (type != null) {
            criteria.andTypeEqualTo(type);
        }
        if (status != null) {
            criteria.andTypeEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);
        if (!StringUtil.isEmpty(sort) && !StringUtil.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        MarketCouponMapper mapper = MyBatisUtil.getMapper(MarketCouponMapper.class);
        PageHelper.startPage(page, limit);

        List<MarketCoupon> marketCoupons = mapper.selectByExample(example);

        return CommonData.data(new PageInfo(marketCoupons));
    }

    @Override
    public BaseRespVo create(MarketCoupon coupon) {
        BaseRespVo error = validate(coupon);
        if (error != null) {
            return error;
        }

        // 如果是兑换码类型，则这里需要生存一个兑换码
        if (coupon.getType().equals(2)) {
            String code = this.generateCode();
            coupon.setCode(code);
        }
        TransactionUtil.startTransaction();
        coupon.setId(null);
        this.add(coupon);
        TransactionUtil.commit();
        return BaseRespVo.ok(coupon);
    }

    @Override
    public int add(MarketCoupon coupon) {
        Date now = new Date();
        coupon.setAddTime(now);
        coupon.setUpdateTime(now);
        MarketCouponMapper couponMapper = TransactionUtil.getMapper(MarketCouponMapper.class);
        return couponMapper.insertSelective(coupon);
    }

    //生成8位字母和数字的组合
    public String generateCode() {
        String code = getRandomNum(8);
        // 保证这个兑换码数据库中没有
        while (findByCode(code) != null) {
            code = getRandomNum(8);
        }
        return code;
    }

    // 根据兑换码查找优惠券
    public MarketCoupon findByCode(String code) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketCouponMapper couponMapper = sqlSession.getMapper(MarketCouponMapper.class);
        MarketCouponExample example = new MarketCouponExample();
        example.or().andCodeEqualTo(code).andTypeEqualTo(new Short("2")).andStatusEqualTo(new Short("0")).andDeletedEqualTo(false);
        List<MarketCoupon> couponList = couponMapper.selectByExample(example);
        sqlSession.close();
        if (couponList.size() > 1) {
            throw new RuntimeException("");
        } else if (couponList.size() == 0) {
            return null;
        } else {
            return couponList.get(0);
        }
    }

    private String getRandomNum(Integer num) {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        base += "0123456789";

        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    private BaseRespVo validate(MarketCoupon coupon) {
        String name = coupon.getName();
        if (StringUtil.isEmpty(name)) {
            return BaseRespVo.badArgument();
        }
        if (coupon.getTimeType() == 1 && (coupon.getStartTime() == null || coupon.getEndTime() == null)) {
            return BaseRespVo.badArgument();
        }
        return null;
    }
}